<?php
// 简单的数据库初始化脚本 - 使用PDO直接连接

// 读取.env文件获取数据库配置
$envFile = __DIR__ . '/.env';
if (!file_exists($envFile)) {
    die(".env文件不存在，无法获取数据库配置\n");
}

$env = parse_ini_file($envFile);

// 数据库连接配置
$host = $env['DB_HOST'] ?? 'localhost';
$port = $env['DB_PORT'] ?? '3306';
$dbname = $env['DB_DATABASE'] ?? 'mingpian';
$username = $env['DB_USERNAME'] ?? 'root';
$password = $env['DB_PASSWORD'] ?? '';

try {
    // 创建PDO连接
    $pdo = new PDO(
        "mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );
    echo "成功连接到数据库: $dbname\n\n";

    // 读取SQL文件内容
    $sqlFile = __DIR__ . '/database/migrations/create_tables.sql';
    if (!file_exists($sqlFile)) {
        die("SQL文件不存在: $sqlFile\n");
    }

    $sqlContent = file_get_contents($sqlFile);

    // 分割SQL语句（处理注释和空行）
    $sqlContent = preg_replace('/--.*$/m', '', $sqlContent); // 移除单行注释
    $sqlContent = preg_replace('/\/\*.*?\*\//s', '', $sqlContent); // 移除多行注释
    
    $sqlStatements = preg_split('/;\s*$/m', $sqlContent, -1, PREG_SPLIT_NO_EMPTY);

    // 执行每个SQL语句
    foreach ($sqlStatements as $statement) {
        $statement = trim($statement);
        if (!empty($statement)) {
            try {
                $pdo->exec($statement);
                echo "执行成功: " . substr($statement, 0, 50) . (strlen($statement) > 50 ? '...' : '') . "\n";
            } catch (PDOException $e) {
                echo "执行失败: " . substr($statement, 0, 50) . (strlen($statement) > 50 ? '...' : '') . "\n";
                echo "错误信息: " . $e->getMessage() . "\n";
            }
        }
    }

    echo "\n数据库初始化完成！\n";
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage() . "\n");
}